package com.springboot.component.dubbo;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.springboot.config.GetIP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

// @Activate 无条件自动激活
@Activate(group = {Constants.PROVIDER, Constants.CONSUMER})
public class DubboLogFilter implements Filter{
	private final Logger log = LoggerFactory.getLogger(DubboExceptionFilter.class);

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		// TODO Auto-generated method stub
		log.info("DubboLogFilter开始");
		Result rs = null;
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String ip = GetIP.getIpAddr(req);
		try {
			RpcContext.getContext().setAttachment("ip",ip);
			rs = invoker.invoke(invocation);
			System.out.println("远程地址ip  "+ip);
		}catch (Exception e) {
			// TODO: handle exception
		}
		log.info("DubboLogFilter结束");

		return rs;
	}


	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}

